package com.example.lab5


import android.annotation.SuppressLint
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.http.GET
import retrofit2.http.Query
import android.os.Bundle
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.ImageView
import android.widget.Spinner
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.HttpException
import retrofit2.converter.gson.GsonConverterFactory
import java.net.URL


class MainActivity : AppCompatActivity() {
    interface CatApiService {
        @GET("images/search")
        suspend fun getRandomCat(@Query("limit") limit: Int = 1, @Query("size") size: String = "full", @Query("mime_types") mimeTypes: String): List<CatImageData>

        data class CatImageData(val id: String, val url: String)
    }
    private val retrofit = Retrofit.Builder()
        .baseUrl("https://api.thecatapi.com/v1/")
        .addConverterFactory(GsonConverterFactory.create())
        .client(OkHttpClient.Builder().addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)).build())
        .build()
    private val catApiService = retrofit.create(CatApiService::class.java)
    private var isResized = false
//    val container_layout_for_images : LinearLayout = findViewById(R.id.image_container)
    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val spinner_mime_types: Spinner = findViewById(R.id.spinner_mime_types)
        val button_refresh : Button = findViewById(R.id.button_refresh)
        val button_refreshTwo :Button = findViewById(R.id.button_refreshTwo)
        val imageViewCat : ImageView = findViewById(R.id.image_view_cat)
        val imageViewCat1 : ImageView = findViewById(R.id.imageView1)
        val imageViewCat2 : ImageView = findViewById(R.id.imageView2)
        val imageViewCat3 : ImageView =  findViewById(R.id.imageView3)
        val imageViewCat4 : ImageView = findViewById(R.id.imageView4)
        val imageViewCat5 : ImageView =findViewById(R.id.imageView5)
        // 初始化Spinner
        val types = arrayOf("gif", "picture", "random")
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, types)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinner_mime_types.adapter = adapter
        spinner_mime_types.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
                getImage(types[position])
            }

            override fun onNothingSelected(parent: AdapterView<*>) {}
        }

        // 设置按钮点击事件
        button_refresh.setOnClickListener {
            imageViewCat1.visibility = View.VISIBLE
            imageViewCat2.visibility = View.VISIBLE
            imageViewCat3.visibility = View.VISIBLE
            imageViewCat4.visibility = View.VISIBLE
            getTwoImages(spinner_mime_types.selectedItem.toString())
        }
        button_refreshTwo.setOnClickListener {
            getImage(spinner_mime_types.selectedItem.toString())
            imageViewCat1.visibility = View.GONE
            imageViewCat2.visibility = View.GONE
            imageViewCat3.visibility = View.GONE
            imageViewCat4.visibility = View.GONE
            if (!isResized) {
                imageViewCat5.layoutParams.width = (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300f, resources.displayMetrics).toInt()).toInt()
                imageViewCat5.layoutParams.height = (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300f, resources.displayMetrics).toInt()).toInt()
                isResized = true
            } else {
                imageViewCat5.layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT
                imageViewCat5.layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
                isResized = false
            }
            imageViewCat5.requestLayout()

    }

    }

    private fun getImage(selectedType: String) {
        val image_view_cat: ImageView = findViewById(R.id.imageView5)

        CoroutineScope(Dispatchers.IO).launch {
            try {
                val formattedType = when (selectedType) {
                    "gif" -> "gif"
                    "picture" -> "picture"
                    "random" -> "random"
                    else -> throw IllegalArgumentException("Invalid MIME type selection.")
                }

                val catData = catApiService.getRandomCat(mimeTypes = formattedType)

                withContext(Dispatchers.Main) {
                    if (catData.isNotEmpty()) {
                        loadGifImage(this@MainActivity, image_view_cat, catData[0].url)
//                        Picasso.get().load(catData[0].url).into(image_view_cat)
                    } else {
                        Toast.makeText(this@MainActivity, "No image found.", Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: HttpException) {
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@MainActivity, "Error fetching image: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@MainActivity, "An unexpected error occurred.", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
    fun loadGifImage(context: Context, imageView: ImageView, imageUrl: String) {
        Glide.with(context)
            .load(imageUrl)
            .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC)) // 自动缓存策略
            .into(imageView)
    }

    // 在MainActivity中的部分代码

    private fun getTwoImages(selectedType: String) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val formattedType = when (selectedType) {
                    "gif" -> "gif"
                    "picture" -> "picture"
                    "random" -> "random"
                    else -> throw IllegalArgumentException("Invalid MIME type selection.")
                }

                val catDataList = catApiService.getRandomCat(limit = 4, mimeTypes = formattedType)

                withContext(Dispatchers.Main) {
                    catDataList.forEachIndexed { index, catImageData ->
                        val imageView = when (index) {
                            0 -> findViewById<ImageView>(R.id.imageView1)
                            1 -> findViewById<ImageView>(R.id.imageView2)
                            2 -> findViewById<ImageView>(R.id.imageView3)
                            3 -> findViewById<ImageView>(R.id.imageView4)
                            4 -> findViewById<ImageView>(R.id.imageView5)
                            else -> return@forEachIndexed // 防止越界
                        }
                        loadGifImage(this@MainActivity, imageView, catImageData.url)
                    }
                }
            } catch (e: HttpException) {
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@MainActivity, "Error fetching images: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@MainActivity, "An unexpected error occurred.", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

}

